package com.supermarket.api.service.impl;

import com.supermarket.api.bean.collection.CollectionRes;
import com.supermarket.api.bean.collection.CollectionReq;
import com.supermarket.api.common.PageParam;
import com.supermarket.api.common.filters.UserCacheManage;
import com.supermarket.api.entity.CollectionEntity;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.repository.CollectionRepository;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.service.CollectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户收藏服务层
 * @author 李其伟
 * @date 2023/11/10
 */
@Slf4j
@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionRepository collectionRepository;

    @Autowired
    private ProductRepository productRepository;

    @Override
    public void createAndDelete(CollectionReq req) {
        Long userId = UserCacheManage.getUserIdCache();
        List<CollectionEntity> list = collectionRepository.findAllByUserIdAndSku(userId,req.getSku());

        //数据库没有查询到，添加
        if(CollectionUtils.isEmpty(list)){
            CollectionEntity entity = new CollectionEntity();
            entity.setUserId(userId);
            entity.setSku(req.getSku());
            entity.setCreateTime(new Date());
            collectionRepository.save(entity);
        }else {
            //查询到就删除
            collectionRepository.deleteInBatch(list);
        }
    }

    @Override
    public void clear() {
        Long userId = UserCacheManage.getUserIdCache();
        List<CollectionEntity> entityList = collectionRepository.findAllByUserId(userId);
        collectionRepository.deleteInBatch(entityList);
    }

    @Override
    public CollectionEntity detail(String sku) {
        Long userId = UserCacheManage.getUserIdCache();
        List<CollectionEntity> list = collectionRepository.findAllByUserIdAndSku(userId,sku);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    @Override
    public Page<CollectionRes> list(PageParam pageParam) {
        Long userId = UserCacheManage.getUserIdCache();
        /**
         * 排序方式
         * 一定要是实体类的属性，而不能是数据库的字段
         */
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        /**
         * 当前页， 每页记录数， 排序方式
         */
        Pageable pageable = PageRequest.of(pageParam.getPageNum() , pageParam.getPageSize(), sort);
        Page<CollectionEntity> collectionEntityPage = collectionRepository.findAllByUserId(userId,pageable);
        List<CollectionEntity> collectionEntityList = collectionEntityPage.getContent();


        //获取产品数据
        List<String> skuList = collectionEntityList.stream().map(CollectionEntity::getSku).collect(Collectors.toList());
        List<ProductEntity> productEntityList = productRepository.findAllBySkuIn(skuList);
        Map<String,ProductEntity> map = productEntityList.stream().collect(Collectors.toMap(ProductEntity::getSku, entity ->entity));

        //设置列表
        List<CollectionRes> collectionResList = new ArrayList<>();
        for(CollectionEntity collectionEntity : collectionEntityList){

            CollectionRes collectionRes = new CollectionRes();

            ProductEntity pe = map.get(collectionEntity.getSku());
            if(pe==null){
                break;
            }
            BeanUtils.copyProperties(pe,collectionRes);
            collectionRes.setCreateTime(collectionEntity.getCreateTime());
            collectionRes.setId(collectionEntity.getId());

            collectionResList.add(collectionRes);
        }

        //重新创建
        return new PageImpl<>(collectionResList,collectionEntityPage.getPageable(),collectionEntityPage.getTotalElements());
    }
}
